<script setup>
import { computed, nextTick, reactive, ref, watch, onMounted } from "vue";
import { useRouter } from "vue-router";
import dayjs from "dayjs";
import { Message } from "@arco-design/web-vue";
import orderApi from "@/api/orderApi";
import goodApi from "@/api/goodApi";
import regionApi from "@/api/regionApi";
import couponApi from "@/api/couponApi";
import constants from "@/utils/constants";
const router = useRouter();

const orderForm = ref();
const searchForm = ref();
const customCakeForm = ref();
const searchModel = reactive({});
const printVisible = ref(false);
const printOrderData = ref({});
const loadingCoupon = ref(false);

const printObj = ref({
  id: "printCon", //这里的id就是上面我们的打印区域id，实现指哪打哪
  popTitle: "订单打印", // 打印配置页上方的标题
  extraHead:
    '<meta http-equiv="Content-Language"content="zh-cn"/>,<style> @page { margin: 0; size: auto; } @media print { body { margin: 0; padding: 10mm; } #printCon { height: auto !important; } } </style>', // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
  preview: false, // 是否启动预览模式，默认是false
  previewTitle: "预览的标题", // 打印预览的标题
  previewPrintBtnLabel: "预览结束，开始打印", // 打印预览的标题下方的按钮文本，点击可进入打印
  zIndex: 20002, // 预览窗口的z-index，默认是20002，最好比默认值更高
  previewBeforeOpenCallback() {
    console.log("正在加载预览窗口！");
  }, // 预览窗口打开之前的callback
  previewOpenCallback() {
    console.log("已经加载完预览窗口，预览打开了！");
  }, // 预览窗口打开时的callback
  beforeOpenCallback() {
    console.log("开始打印之前！");
  }, // 开始打印之前的callback
  openCallback() {
    console.log("执行打印了！");
  }, // 调用打印时的callback
  closeCallback() {
    console.log("关闭了打印工具！");
  }, // 关闭打印的callback(无法区分确认or取消)
  clickMounted() {
    console.log("点击v-print绑定的按钮了！");
  },
});

const printOrder = (record) => {
  printVisible.value = true;
  printOrderData.value = Object.assign({}, record);
  let tel = record.tel;
  let addTimeTxts = record.addTimeText.split(" ");
  printOrderData.value.addTimeDate = addTimeTxts[0];
  printOrderData.value.addTimeTxt = addTimeTxts[1];
  printOrderData.value.printTel = tel.substring(0, 3) + " " +
    tel.substring(3, 7) + " " + tel.substring(7)
  let customGoodList = record.goodList.filter(item => item.goodsSn.includes("P29"))
  if (customGoodList && customGoodList.length > 0) {
    printOrderData.value.isCustom = true;
  }
};

const canDowload = computed(
  () =>
    (searchModel.addEndDate && searchModel.addStartDate) ||
    searchModel.shippingDate
);

const searchGoodModel = reactive({
  isOnSale: true,
  catIds: [],
  catId: ""
});
const customCakeDialog = ref(false);
const visible = ref(false);
const isView = ref(false);
const dialogTitle = ref('创建订单')
const downloading = ref(false);
const regionData = ref([]);
const customCakeData = reactive({});
const couponList = ref([]);

const areaFieldNames = { value: "regionId", label: "regionName" };
let orderInfo = ref({
  submitUserPhone: "4009998611",
  goodList: [],
  discount: 0.00
});
const loading = ref(false);
const histroyLoading = ref(false);
const histroyVisible = ref(false);
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 10,
  showPageSize: true,
  pageSizeOptions: [10, 25, 30, 50],
  showTotal: true,
  pageChange: (current) => {
    pagination.current = current;
    search(current, pagination.pageSize);
  },
  pageSizeChange(size) {
    pagination.pageSize = size;
    search(pagination.current, size);
  },
});

const histroyPagination = reactive({
  total: 0,
  current: 1,
  pageSize: 10,
  showPageSize: true,
  pageSizeOptions: [10, 25, 30, 50],
  showTotal: true,
  pageChange: (current) => {
    histroyPagination.current = current;
    searchHistroy();
  },
  pageSizeChange(size) {
    histroyPagination.pageSize = size;
    searchHistroy();
  },
});

const histroyData = ref([]);
const historySearchParam = ref({});
const openHistroyDialog = (record) => {
  histroyVisible.value = true;
  historySearchParam.value = {
    userId: record.userId
  }
  searchHistroy();
}


const searchHistroy = () => {
  var params = {
    pageNo: histroyPagination.current,
    pageSize: histroyPagination.pageSize,
    queryParam: Object.assign({}, historySearchParam.value),
  };
  histroyLoading.value = true;
  orderApi.queryPage(params).then((res) => {
    histroyData.value = res.records;
    histroyPagination.total = res.total;
    histroyLoading.value = false;
  });
}

const goodPagination = reactive({
  total: 0,
  current: 1,
  pageSize: 16,
  showPageSize: true,
  pageSizeOptions: [16, 25, 30, 50],
  showTotal: true,
  pageChange: (current) => {
    goodPagination.current = current;
    searchGoods(current, goodPagination.pageSize);
  },
  pageSizeChange(size) {
    goodPagination.pageSize = size;
    searchGoods(goodPagination.current, size);
  },
});

const columns = [
  {
    title: "订单号",
    dataIndex: "orderSn",
    width: 130,
  },
  {
    title: "订单时间",
    slotName: "addTimeText",
    width: 220,
  },
  {
    title: "收货信息",
    slotName: "consignee",
    width: 300,
  },
  {
    title: "商品信息",
    slotName: "productInfo",
    width: 300,
  },
  {
    title: "配送员",
    slotName: "shippingName",
    width: 80,
  },
  {
    title: "支付信息",
    slotName: "payInfo",
    width: 150,
  },
  {
    title: "订单金额",
    slotName: "orderMoney",
    width: 120,
  },
  {
    title: "订单状态",
    dataIndex: "orderStatusStr",
    width: 100,
  },
  {
    title: "操作",
    slotName: "action",
    fixed: "right",
    // width: 200,
  },
];

const histroyColumns = [
  {
    title: "订单号",
    dataIndex: "orderSn",
    width: 130,
  },
  {
    title: "订单时间",
    slotName: "addTimeText",
    width: 220,
  },
  {
    title: "收货信息",
    slotName: "consignee",
    width: 300,
  },
  {
    title: "商品信息",
    slotName: "productInfo",
    width: 300,
  },
  {
    title: "配送员",
    slotName: "shippingName",
    width: 80,
  },
  {
    title: "支付信息",
    slotName: "payInfo",
    width: 150,
  },
  {
    title: "订单金额",
    slotName: "orderMoney",
    width: 120,
  },
  {
    title: "订单状态",
    dataIndex: "orderStatusStr",
    width: 100,
  },
  {
    title: "操作",
    slotName: "action",
    fixed: "right",
    width: 200,
  },
];

const data = ref([]);
const goodList = ref([]);

const getByCouponId = (couponId) => {
  couponApi.queryById({
    couponId: couponId
  }).then(res => {
    orderInfo.value.discount = parseFloat(res.value);
    countOrderAmount();
  });
}

const searchCoupon = (value) => {
  if (!value || !value.trim()) {
    couponList.value = [];
  } else {
    loadingCoupon.value = true;
    couponApi.queryPage({
      pageNo: 1,
      pageSize: 200,
      queryParam: {
        searchKey: value
      }
    }).then(res => {
      let coupons = [];
      res.records.forEach(c => {
        coupons.push({
          value: c.couponId,
          label: c.name
        });
      })
      couponList.value = coupons;
      loadingCoupon.value = false;
    })
  }
}

const showAddDialog = () => {
  visible.value = true;
  orderForm.value.resetFields();
  orderInfo.value = {
    submitUserPhone: "4009998611",
    goodList: [],
    payId: 106,
    discount: 0.00
  };
  searchGoods(1, 16);
};

const editRecord = async (record) => {
  visible.value = true;
  isView.value = false;
  dialogTitle.value = "编辑订单"
  let orderRecord = await orderApi.queryDetail({ orderId: record.orderId });
  nextTick(() => {
    orderForm.value.resetFields();
    orderInfo.value = Object.assign({}, orderRecord);
    orderInfo.value.citys = [orderRecord.province, orderRecord.city, orderRecord.district];
  });
};

const viewRecord = (record) => {
  visible.value = true;
  isView.value = true;
  dialogTitle.value = "查看订单"
  searchGoods(1, 16);
  nextTick(() => {
    orderForm.value.resetFields();
    orderInfo.value = Object.assign({}, record);
    orderInfo.value.citys = [record.province, record.city, record.district];
  });
}

const submiting = ref(false)
const handleSubmitSuccess = (values, e) => {
  let me = this;
  if (!orderInfo.value.shippingDay) {
    Message.warning("请选择送货日期");
    return;
  }
  if (!orderInfo.value.shippingHour) {
    Message.warning("请选择送货时间");
    return;
  }

  submiting.value = true

  values.province = values.citys[0];
  values.city = values.citys[1];
  values.district = values.citys[2];
  orderApi.save(values).then((res) => {
    visible.value = false;
    Message.success("保存成功");
    search(1, 10);
    submiting.value = false
  }).catch(() => {
    submiting.value = false
  });
};

const addCustomCakeGood = (values, e) => {
  customCakeData.marketPrice = values.goodsPrice;
  orderInfo.value.postscript = values.cakeDesc;
  orderInfo.value.discount = orderInfo.value.discount;
  let findOrderGood = orderInfo.value.goodList.find((item) => {
    return item.goodsAttr == values.goodsAttr && item.goodsId == values.goodsId;
  });

  if (findOrderGood) {
    findOrderGood.goodsNumber = +findOrderGood.goodsNumber + 1;
  } else {
    orderInfo.value.goodList.push(values);
  }

  countOrderAmount();

  customCakeDialog.value = false;

}

const queryFlavors = async (goodsId) => {
  return await goodApi.queryFlavors({ goodsId: goodsId });
}

const addOrderGood = async (good, attrInfo) => {

  if (good.goodsSn == 'P2900001') {
    customCakeDialog.value = true;
    customCakeData.goodsName = good.goodsName;
    customCakeData.goodsSn = good.goodsSn;
    customCakeData.goodsId = good.goodsId;
    customCakeData.goodsThumb = good.goodsThumb;
    customCakeData.goodsNumber = 1;
    customCakeForm.value.resetFields();
  } else {

    let flavors = await queryFlavors(good.goodsId);

    let orderGoodItem = {
      goodsName: good.goodsName,
      goodsSn: good.goodsSn,
      goodsId: good.goodsId,
      goodsAttrId: attrInfo.goodsAttrId,
      marketPrice: attrInfo.attrPrice,
      goodsPrice: attrInfo.attrPrice,
      goodsNumber: 1,
      goodsAttr: !attrInfo.attrDesc ? attrInfo.attrName : attrInfo.attrDesc,
      goodsThumb: good.goodsThumb,
      flavors: flavors,
      flavorName: flavors && flavors.length > 0 ? flavors[0].flavorName : "",
    };

    let findOrderGood = orderInfo.value.goodList.find((item) => {
      return item.goodsAttrId == attrInfo.goodsAttrId;
    });

    if (findOrderGood) {
      findOrderGood.goodsNumber = +findOrderGood.goodsNumber + 1;
    } else {
      orderInfo.value.goodList.push(orderGoodItem);
    }
    countOrderAmount();
  }
};

const generateRowClass = (record, rowIndex) => {
  if (record.orderStatus == 8) {
    return "cancel-order-row";
  }
  return "";
};

const substactGood = (good) => {
  let findOrderGood = orderInfo.value.goodList.find((item) => {
    return item.goodsAttrId == good.goodsAttrId;
  });
  if (findOrderGood) {
    findOrderGood.goodsNumber--;
    if (findOrderGood.goodsNumber <= 0) {
      let findOrderGoodIndex = orderInfo.value.goodList.findIndex((item) => {
        return item.goodsAttrId == good.goodsAttrId;
      });
      orderInfo.value.goodList.splice(findOrderGoodIndex, 1);
    }
  }
  countOrderAmount();
};

const addGoodNumber = (good) => {
  good.goodsNumber++;
  countOrderAmount();
};

const countOrderAmount = () => {
  let goodsAmount = 0.0;
  let moneyPaid = 0.0;
  let discountAmount = parseFloat(orderInfo.value.discount);
  orderInfo.value.goodList.forEach((item) => {
    goodsAmount =
      goodsAmount + parseFloat(item.goodsPrice) * parseInt(item.goodsNumber);
  });
  moneyPaid = goodsAmount - discountAmount;
  console.log(goodsAmount, moneyPaid);
  if (moneyPaid < 0) {
    moneyPaid = 0;
  }
  orderInfo.value.goodsAmount = goodsAmount;
  orderInfo.value.moneyPaid = moneyPaid;
  orderInfo.value.discount = discountAmount;
};

const search = (current = 1, size = 15) => {
  var params = {
    pageNo: current,
    pageSize: size,
    queryParam: Object.assign({}, searchModel),
  };
  loading.value = true;
  orderApi.queryPage(params).then((res) => {
    data.value = res.records;
    pagination.total = res.total;
    loading.value = false;
  });
};

const searchGoods = (current = 1, size = 15) => {
  let searchParams = Object.assign({}, searchGoodModel);
  if (searchParams.catId) {
    if (searchParams.catId == '2230') {
      searchParams.catIds = [22, 30];
      searchParams.catId = "";
    } else {
      searchParams.catIds = [searchParams.catId];
    }
  }
  var params = {
    pageNo: current,
    pageSize: size,
    queryParam: searchParams,
  };
  loading.value = true;
  goodApi.queryPage(params).then((res) => {
    goodList.value = res.records;
    goodPagination.total = res.total;
    loading.value = false;
  });
};

const queryRegionTree = () => {
  regionApi.queryTree({}).then((res) => {
    regionData.value = res;
  });
};

const sureOrder = (record) => {
  orderApi
    .sureOrder({
      orderId: record.orderId,
    })
    .then((res) => {
      search(1, 10);
      Message.success("操作成功");
    });
};

const cancel = (record) => {
  orderApi
    .cancel({
      orderId: record.orderId,
    })
    .then((res) => {
      search(1, 10);
      Message.success("操作成功");
    });
};

const exportList = () => {
  downloading.value = true;
  orderApi.orderExport(searchModel).then((res) => {
    downloading.value = false;
    const content = res.data;
    const blob = new Blob([content], { type: "application/octet-stream" });
    const fileName =
      "订单列表导出-" + dayjs().format("YYYYMMDDHHmmss") + ".xlsx";

    if (typeof window.navigator.msSaveBlob !== "undefined") {
      window.navigator.msSaveBlob(blob, fileName);
    } else {
      const fileUrl = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = fileUrl;
      a.target = "_blank";
      a.download = fileName;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    }
  });
};

const reset = () => {
  searchForm.value.resetFields();
  searchModel.addEndDate = "";
  search(1, 10);
};

watch(
  searchGoodModel,
  (newVal) => {
    searchGoods(1, 16);
  },
  { immdiate: true, deep: true }
);

search(1, 10);
queryRegionTree();

onMounted(() => {
  setInterval(() => {
    search(1, 10);
  }, 180000);
});

</script>

<template>
  <div class="main-con">
    <a-card>
      <a-row>
        <a-col :flex="1">
          <a-form ref="searchForm" :model="searchModel" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }"
            label-align="left" layout="vertical">
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="name" label="订单号">
                  <a-input v-model="searchModel.orderSn" allow-clear placeholder="请输入订单号" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="tel" label="收货人手机号">
                  <a-input allow-clear v-model="searchModel.tel" placeholder="请输入收货人手机号" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="consignee" label="收货人姓名">
                  <a-input allow-clear v-model="searchModel.consignee" placeholder="请输入收货人姓名" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="userName" label="订货人手机号">
                  <a-input allow-clear v-model="searchModel.userName" placeholder="请输入订货人手机号" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="addStartDate" label="下单日期">
                  <a-space>
                    <a-date-picker v-model="searchModel.addStartDate" placeholder="请选择开始日期" />
                    <a-date-picker v-model="searchModel.addEndDate" placeholder="请选择结束日期" />
                  </a-space>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="shippingDate" label="送货日期">
                  <a-date-picker v-model="searchModel.shippingDate" placeholder="请选择送货日期" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="couponId" label="优惠券码">
                  <a-input allow-clear v-model="searchModel.couponId" placeholder="请输入优惠券码" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="orderStatus" label="订单状态">
                  <a-select v-model="searchModel.orderStatus" placeholder="请选择">
                    <a-option value="">全部</a-option>
                    <a-option value="2">已下单</a-option>
                    <a-option value="8">已取消(已退款)</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 84px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" @click="search(1, 15)">
              <template #icon>
                <icon-search />
              </template>
              查询
            </a-button>
            <a-button @click="reset">
              <template #icon>
                <icon-refresh />
              </template>
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>
    </a-card>
    <a-card style="margin-top: 10px">
      <div class="toolbar">
        <a-space>
          <a-button type="primary" @click="showAddDialog">
            <template #icon>
              <icon-plus />
            </template>
            创建订单
          </a-button>
          <a-button :loading="downloading" :disabled="!canDowload" type="outline" @click="exportList">
            <template #icon>
              <icon-download />
            </template>
            {{ downloading ? "正在导出" : "导出订单" }}
          </a-button>
        </a-space>
      </div>
      <a-table :columns="columns" row-key="orderId" :loading="loading" :data="data" @page-change="pagination.pageChange"
        @page-size-change="pagination.pageSizeChange" :pagination="pagination" :bordered="false"
        :row-class="generateRowClass">
        <template #action="{ record }">
          <a-space>
            <a-button v-if="record.orderStatus == 8" style="width: 60px" size="mini"
              @click="viewRecord(record)">查看</a-button>
            <a-button :disabled="record.orderStatus == 8" style="width: 60px" size="mini"
              @click="editRecord(record)">编辑</a-button>
            <a-button @click="printOrder(record)" size="mini"
              :disabled="record.orderStatus >= 2 && record.orderStatus == 8">打印</a-button>
            <a-popconfirm content="确定取消该订单吗？" @ok="cancel(record)">
              <a-button style="width: 60px" v-if="record.orderStatus != 8" size="mini">{{
                record.orderStatus == 8 ? "已取消" : "取消" }}</a-button>
            </a-popconfirm>
            <a-popconfirm content="确认已联系客户吗？" @ok="sureOrder(record)">
              <a-button style="width: 60px" v-if="!record.packId && record.orderStatus != 8" size="mini">{{
                record.packId ? "已确认" : "确认" }}</a-button>
            </a-popconfirm>
          </a-space>
        </template>
        <template #addTimeText="{ record }">
          <div class="record-item">
            <div>
              <span class="addtime">下单:</span>{{ record.addTimeText }}
            </div>
            <div class="weight">
              <span>收货:</span>{{ record.shippingText }}
            </div>
          </div>
        </template>
        <template #shippingName="{ record }">
          <div class="record-item">
            <div>
              {{ record.shippingName ? record.shippingName : "—" }}
            </div>
          </div>
        </template>
        <template #payInfo="{ record }">
          <div class="record-item">
            <div>
              <span class="addtime">支付方式:</span>{{ record.payName }}
            </div>
            <div>
              <span class="addtime">支付状态:</span>{{ record.payStatus == 2 ? "已支付" : "未支付" }}
            </div>
          </div>
        </template>
        <template #orderMoney="{ record }">
          <div class="record-item">
            <div>
              <span class="addtime">订单:¥</span>{{ record.goodsAmount }}
            </div>
            <div><span class="addtime">应付:¥</span>{{ record.moneyPaid }}</div>
          </div>
        </template>
        <template #consignee="{ record }">
          <div class="record-item">
            <div>
              收货人：{{ record.consignee }} 【<span style="font-weight: 600">{{
                record.tel
              }}</span>】
            </div>
            <div style="font-size: 12px; padding-left: 48px">
              {{ record.address }}
            </div>
            <div class="flex flex-v-center" style="font-size: 12px">
              下单人：【<span>{{
                record.userName == "4009998611" ? "管理员" : record.userName
              }}</span>】
              <a-tag v-if="record.isFirst" color="orange" size="small" bordered>
                <template #icon>
                  <icon-star style="color: orange" />
                </template>
                首单
              </a-tag>
              <a-tag style="cursor: pointer;" @click="openHistroyDialog(record)"
                v-if="!record.isFirst && record.userName != '4009998611'" size="small" color="orange">{{ '下过' +
                  record.buyOrderNumber + '单' }}</a-tag>
            </div>
          </div>
        </template>
        <template #productInfo="{ record }">
          <div class="record-item">
            <div v-for="item in record.goodList" :key="item.goodsAttrId">
              <div
                v-if="!item.goodsSn.includes('P25') && !item.goodsSn.includes('P22') && !item.goodsSn.includes('P24')">
                <span style="font-weight: 600;">{{ item.goodsName }}</span> {{ item.goodsAttr }} x {{ item.goodsNumber
                }}
              </div>
            </div>
          </div>
        </template>
      </a-table>
    </a-card>
  </div>
  <a-modal title="添加定制蛋糕属性" v-model:visible="customCakeDialog" :footer="null">
    <a-form ref="customCakeForm" :model="customCakeData" @submit-success="addCustomCakeGood">
      <a-form-item field="goodsAttr" label="尺寸" :rules="[{ required: true, message: '请输入蛋糕尺寸' }]">
        <a-input v-model="customCakeData.goodsAttr" placeholder="请输入蛋糕尺寸"></a-input>
      </a-form-item>
      <a-form-item field="flavorName" label="夹心" :rules="[{ required: true, message: '请输入蛋糕夹心' }]">
        <a-input v-model="customCakeData.flavorName" placeholder="请输入蛋糕夹心"></a-input>
      </a-form-item>
      <a-form-item field="goodsPrice" label="价格" :rules="[{ required: true, message: '请输入蛋糕价格' }]">
        <a-input-number v-model="customCakeData.goodsPrice" :precision="2" placeholder="请输入蛋糕价格"></a-input-number>
      </a-form-item>
      <a-form-item field="cakeDesc" label="要求" :rules="[{ required: true, message: '请输入蛋糕要求描述' }]">
        <a-textarea :auto-size="true" style="height:150px" v-model="customCakeData.cakeDesc" :rows="5"
          placeholder="请输入蛋糕要求描述"></a-textarea>
      </a-form-item>
      <a-form-item>
        <a-space>
          <a-button type="primary" html-type="submit">保存</a-button>
          <a-button @click="customCakeDialog = false">取消</a-button>
        </a-space>
      </a-form-item>
    </a-form>
  </a-modal>
  <a-modal :title="dialogTitle" v-model:visible="visible" :mask-closable="false" width="1200px" :footer="null"
    :hide-title="false">
    <div class="create-order-con">
      <div style="height: 730px" class="flex flex1">
        <div :span="18" class="flex1" style="height: 730px; overflow: auto;position: relative;">
          <a-card title="">
            <a-empty v-if="!orderInfo.goodList || orderInfo.goodList.length == 0"></a-empty>
            <a-grid v-else :cols="{ xs: 1, sm: 5, md: 5, lg: 5, xl: 5, xxl: 5 }" :colGap="16" :rowGap="16"
              style="background-color: #f0f0f0; padding: 10px">
              <a-grid-item v-for="good in orderInfo.goodList" :key="good.goodsId + good.goodsAttr"
                style="background-color: #fff">
                <div class="buy-good-item flex flex-column flex-center">
                  <div class="good-img">
                    <img style="height: 140px" :src="constants.imgDomain + good.goodsThumb + '?imageslim'
                      " alt="" />
                    <div class="good-attrs">
                      <a-tag style="margin-left: 10px">
                        <span style="color: #666">{{ good.goodsAttr }}</span>
                      </a-tag>
                      <span style="width: 5px"></span>
                      <span>
                        <a-button :disabled="isView" @click="substactGood(good)" size="mini" style="border-radius: 0">
                          <template #icon>
                            <icon-minus></icon-minus>
                          </template>
                        </a-button>
                      </span>
                      <a-input :disabled="isView" v-model="good.goodsNumber" size="mini"
                        style="width: 40px; border-radius: 0" readonly>
                      </a-input>
                      <span>
                        <a-button :disabled="isView" @click="addGoodNumber(good)" size="mini" style="border-radius: 0">
                          <template #icon>
                            <icon-plus></icon-plus>
                          </template>
                        </a-button>
                      </span>
                    </div>
                  </div>
                  <div class="good-info">
                    <div class="good-name">{{ good.goodsName }}</div>
                    <div style="color: yellow; padding: 0 5px">
                      <span>{{ "¥" + good.goodsPrice }}</span>
                      <span v-if="good.flavorName" style="margin-left: 4px">{{ good.flavorName }}</span>
                    </div>
                    <div v-if="good.flavors && good.flavors.length > 0">
                      <a-radio-group size="mini" v-model="good.flavorName">
                        <a-radio v-for="flavor in good.flavors" style="font-size:12px;" :key="flavor.flavorId"
                          :value="flavor.flavorName">
                          <span style="color: #fff !important">{{ flavor.flavorName }}</span>
                        </a-radio>
                      </a-radio-group>
                    </div>
                  </div>
                </div>
              </a-grid-item>
            </a-grid>
          </a-card>
          <a-form :disabled="isView" ref="orderForm" size="large" layout="vertical" :model="orderInfo"
            style="margin-top: 16px; position: relative" @submit-success="handleSubmitSuccess">
            <a-card title="" style="margin-bottom:80px">
              <a-row :gutter="10">
                <a-col :span="8">
                  <a-form-item field="submitUserPhone" label="订货人手机号"
                    :rules="[{ required: true, message: '请输入订货人手机号' }]">
                    <a-input-search v-model="orderInfo.submitUserPhone" placeholder="请输入订货人手机号" search-button />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item field="tel" label="收货人手机号" :rules="[{ required: true, message: '请输入收货人手机' }]">
                    <a-input v-model="orderInfo.tel" placeholder="请输入收货人手机号" />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item field="consignee" label="收货人姓名" :rules="[{ required: true, message: '请输入收货人姓名' }]">
                    <a-input v-model="orderInfo.consignee" placeholder="请输入收货人姓名" />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item field="citys" label="所属地区" :rules="[
                    {
                      type: 'array',
                      minLength: 3,
                      required: true,
                      message: '请选择所属地区',
                    },
                  ]">
                    <a-cascader v-model="orderInfo.citys" :field-names="areaFieldNames" :path-mode="true"
                      expand-trigger="click" :options="regionData" placeholder="请选择所属地区" />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item field="address" label="收货地址">
                    <a-input v-model="orderInfo.address" placeholder="请输入收货地址" />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item field="shippingHour" label="期望收货时间">
                    <a-space>
                      <a-date-picker style="width: 122px" v-model="orderInfo.shippingDay" format="YYYY-MM-DD"
                        placeholder="收货日期" />
                      <a-divider></a-divider>
                      <a-select v-model="orderInfo.shippingHour" allow-clear placeholder="收货时间">
                        <a-option v-for="item in constants.shippingHourList" :key="item.value" :value="item.value"
                          :label="item.label"></a-option>
                      </a-select>
                    </a-space>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item field="cardName" label="贺卡内容">
                    <a-textarea v-model="orderInfo.cardName" placeholder="请输入贺卡内容" />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item field="payId" label="支付方式" style="margin-bottom: 5px;">
                    <a-select :disabled="orderInfo.referer == '小程序'" v-model="orderInfo.payId">
                      <a-option v-for="item in constants.payMethods" :key="item.value" :value="item.value"
                        :label="item.label"></a-option>
                    </a-select>
                  </a-form-item>
                  <a-form-item field="couponName" label="优惠券">
                    <a-select v-if="!orderInfo.orderId" :loading="loadingCoupon" @change="getByCouponId" allow-clear
                      allow-search placeholder="输入券码搜索选择" @search="searchCoupon" :filter-option="false">
                      <a-option v-for="c in couponList" :key="c.value" :value="c.value" :label="c.label"></a-option>
                    </a-select>
                    <a-input v-else :readonly="orderInfo.referer == '小程序' || orderInfo.couponId"
                      v-model="orderInfo.couponName" placeholder="请输入优惠券码" />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item field="postscript" label="订单备注">
                    <a-textarea v-model="orderInfo.postscript" :auto-size="true" style="height:120px"
                      placeholder="请输入订单备注" />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-card>
            <div v-if="!isView" class="option-btn">
              <a-space>
                <div :span="12">订单：<span style="color: #f60">¥{{ orderInfo.goodsAmount }}</span></div>
                <div :span="12">应付：<span style="color: #f60">¥{{ orderInfo.moneyPaid }}</span></div>
                <div :span="12">优惠：<span style="color: #f60">¥{{ orderInfo.discount }}</span></div>
                <div style="width:50px"></div>
                <a-button html-type="submit" :loading="submiting" :disabled="submiting" type="primary">保存</a-button>
                <a-button @click="() => {
                  visible = false;
                }
                ">取消</a-button>
              </a-space>
            </div>
          </a-form>
        </div>
        <div :span="6" class="good-content">
          <div class="goods-con">
            <div class="search-con">
              <a-form :model="searchGoodModel" layout="vertical">
                <a-row :gutter="10">
                  <a-col :span="24">
                    <a-form-item field="catId" label="商品名称">
                      <a-input-search placeholder="输入商品名称查询" v-model="searchGoodModel.goodsName"></a-input-search>
                    </a-form-item>
                  </a-col>
                  <a-col :span="12">
                    <a-form-item field="catId" label="商品分类">
                      <a-select v-model="searchGoodModel.catId" allow-clear placeholder="请选择"
                        :options="constants.catList">
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <a-col :span="12">
                    <a-form-item field="isOnSale" label="是否上架">
                      <a-select v-model="searchGoodModel.isOnSale" allow-clear placeholder="请选择"
                        :options="constants.onSaleStatues">
                      </a-select>
                    </a-form-item>
                  </a-col>
                </a-row>
              </a-form>
            </div>
            <a-row :gutter="10">
              <a-col :span="12" v-for="good in goodList" :key="good.id">
                <div class="good-item flex flex-column flex-center">
                  <div class="good-img">
                    <a-image :preview="false" width="100%" height="126.5px" :src="constants.imgDomain +
                      good.goodsThumb +
                      '?imageslim/zlevel/7'
                      " alt="" />
                    <div v-if="good.goodsSn != 'P2900001'" class="good-attrs">
                      <a-button size="mini" type="primary" status="success" @click="addOrderGood(good, attr)"
                        class="good-attr-btn" v-for="attr in good.goodAttrList" :key="attr.goodsAttrId">
                        <template #icon>
                          <icon-check size="12" style="color: #fff" />
                        </template>
                        {{ attr.attrDesc ? attr.attrDesc : attr.attrName }}
                      </a-button>
                    </div>
                    <div v-else class="good-attrs">
                      <a-button size="mini" type="primary" status="success" @click="addOrderGood(good, attr)"
                        class="good-attr-btn">
                        <template #icon>
                          <icon-plus size="12" style="color: #fff" />
                        </template>
                      </a-button>
                    </div>
                  </div>
                  <div class="good-info">
                    <div>{{ good.goodsName }}</div>
                  </div>
                </div>
              </a-col>
            </a-row>
          </div>
          <div class="footer-page">
            <a-pagination :total="goodPagination.total" simple @change="goodPagination.pageChange"
              @page-size-change="goodPagination.pageSizeChange" :show-total="true" />
          </div>
        </div>
      </div>
    </div>
  </a-modal>

  <a-drawer title="打印订单" :width="880" v-model:visible="printVisible" :destroy-on-close="true"
    :footer-style="{ textAlign: 'right' }" :bodyStyle="{ 'padding-top': '0px' }">
    <div id="printCon" style="width: 210mm; padding: 0 10px">
      <div style="font-size: 13px; border: 1px solid #000; padding: 16px">
        <div style="display: flex">
          <div style="width: 100px; padding-right: 16px">
            <img src="../../assets/logo.png" style="width: 100%" alt="" />
          </div>
          <div>
            <div>
              Thanks for ordering from Reverie. We`re happy to meet you and
              would love to hear from your if you have any feedback or
              suggestions. We hope to see you again soon, dream to meet you.
            </div>
            <div>
              非常感谢您在浮遇纪的选购！很高兴遇见您，您的任何意见与建议都将帮助我们更好的成长，遇见心，方知味，期待再次与您的相遇.
            </div>
          </div>
        </div>
      </div>
      <div style="
          font-size: 14px;
          padding: 16px;
          border: 1px solid #000;
          border-top: none;
          height: 120px;
        ">
        <div style="float: left; width: 50%; text-align: left">
          <div style="
              font-weight: 600;
              font-size: 16px;
              padding: 10px 0;
              margin-left: 8px;
            ">
            客户留存联
          </div>
          <div style="margin-left: 8px">
            订单号：{{ printOrderData.orderSn }}
          </div>
          <div style="text-align: left">
            <vue-barcode :value="printOrderData.orderSn" :options="{
              displayValue: false,
              height: 40,
              lineColor: '#333333',
            }"></vue-barcode>
          </div>
        </div>
        <div style="float: right; width: 50%; padding-top: 30px; text-align: right">
          <div>
            <span style="width: 200px; display: inline-block; text-align: right">Order Date（订单日期）：</span>
            <span style="font-size: 18px;font-weight: 600;">{{ printOrderData.addTimeDate }}</span>
            <span>{{ " " + printOrderData.addTimeTxt }}</span>
          </div>
          <div style="margin: 8px 0">
            <span style="width: 200px; display: inline-block; text-align: right;">Delivery Date（送货日期）：</span>
            <span style="font-size: 18px;font-weight: 600;">{{ printOrderData.shippingDay }}</span>
          </div>
          <div>
            <span style="width: 200px; display: inline-block; text-align: right">Delivery Time（送货时间）：</span>{{
              printOrderData.shippingHour +
              ":00 ~ " +
              (printOrderData.shippingHour + 1) +
              ":00"
            }}
          </div>
        </div>
        <div style="clear: both"></div>
      </div>
      <div style="border: 1px solid #000; border-top: none; padding: 0">
        <div style="border-bottom: 1px solid #000">
          <span style="
              border-right: 1px solid #000;
              padding: 0 16px;
              width: 200px;
              display: inline-block;
              padding: 10px 16px;
            ">Customer（客户）</span>
          <span style="padding: 0 16px;font-size: 16px;font-weight: 600;">{{ printOrderData.consignee }}</span>
        </div>
        <div style="border-bottom: 1px solid #000">
          <span style="
              border-right: 1px solid #000;
              padding: 0 16px;
              width: 200px;
              display: inline-block;
              padding: 5px 16px;
            ">Deliver Address（送货地址）</span>
          <span style="padding: 0 16px">{{ printOrderData.cityName + printOrderData.districtName +
            printOrderData.address
          }}</span>
        </div>
        <div style="border-bottom: 1px solid #000">
          <span style="
              border-right: 1px solid #000;
              padding: 0 16px;
              width: 200px;
              display: inline-block;
              padding: 5px 16px;
            ">Mobile（手机）</span>
          <span style="padding: 0 16px;font-size: 16px;font-weight: 600;">{{ printOrderData.printTel }}</span>
        </div>
        <div style="border-bottom: 1px solid #000">
          <span style="
              border-right: 1px solid #000;
              padding: 0 16px;
              width: 200px;
              display: inline-block;
              padding: 5px 16px;
            ">Payment Mtd（付款方式）</span>
          <span style="padding: 0 16px">{{ printOrderData.payName }}</span>
        </div>
        <div>
          <span style="
              border-right: 1px solid #000;
              padding: 0 16px;
              width: 200px;
              display: inline-block;
              padding: 5px 16px;
            ">Balance Due（应付总额）</span>
          <span style="padding: 0 16px; font-weight: 600">¥{{ printOrderData.moneyPaid }}</span>
        </div>
      </div>
      <div style="margin-top: 16px">
        <div style="font-weight: 600; padding: 10px 0">订单明细：</div>
        <div style="border: 1px solid #000">
          <div style="display: flex; border-bottom: 1px solid #000">
            <div style="
                width: 50px;
                text-align: center;
                border-right: 1px solid #000;
                padding: 10px 0;
              ">
              #
            </div>
            <div style="
                width: 150px;
                text-align: center;
                border-right: 1px solid #000;
                padding: 10px 0;
              ">
              商品编码
            </div>
            <div style="
                flex: 1;
                text-align: center;
                border-right: 1px solid #000;
                padding: 10px 0;
              ">
              商品名称
            </div>
            <div style="
                width: 100px;
                text-align: center;
                border-right: 1px solid #000;
                padding: 10px 0;
              ">
              单位规格
            </div>
            <div style="
                width: 80px;
                text-align: center;
                border-right: 1px solid #000;
                padding: 10px 0;
              ">
              数量
            </div>
            <div style="
                width: 80px;
                text-align: center;
                border-right: 1px solid #000;
                padding: 10px 0;
              ">
              单价
            </div>
            <div style="width: 80px; text-align: center; padding: 10px 0">
              总价
            </div>
          </div>
          <div v-for="(item, index) in printOrderData.goodList" :key="item.goodsSn" style="display: flex">
            <div style="
                width: 50px;
                text-align: center;
                border-right: 1px solid #000;
                padding: 10px 0;
              ">
              {{ index + 1 }}
            </div>
            <div style="
                width: 150px;
                text-align: center;
                border-right: 1px solid #000;
                padding: 10px 0;
              ">
              {{ item.goodsSn }}
            </div>
            <div style="
                flex: 1;
                text-align: center;
                border-right: 1px solid #000;
                padding: 10px 0;
                font-size: 16px;font-weight: 600;
              ">
              {{ item.goodsName }}
            </div>
            <div style="
                width: 100px;
                text-align: center;
                border-right: 1px solid #000;
                padding: 10px 0;
                font-size: 16px;font-weight: 600;
              ">
              {{ item.goodsAttr }}
            </div>
            <div style="
                width: 80px;
                text-align: center;
                border-right: 1px solid #000;
                padding: 10px 0;
              ">
              {{ item.goodsNumber }}
            </div>
            <div style="
                width: 80px;
                text-align: center;
                border-right: 1px solid #000;
                padding: 10px 0;
              ">
              ¥{{ item.goodsPrice }}
            </div>
            <div style="width: 80px; text-align: center; padding: 10px 0">
              ¥{{ item.goodsPrice * item.goodsNumber }}
            </div>
          </div>
        </div>
      </div>
      <div style="margin-top: 16px">
        <div style="float: left; width: 50%">
          <div style="margin-top: 10px; border-bottom: 1px solid #000">
            支付方式：{{ printOrderData.payName }}。{{
              printOrderData.payStatus == 2 ? "已支付，不用收款" : "未支付"
            }}
          </div>
          <div style="margin-top: 10px; border-bottom: 1px solid #000">
            贺卡内容：{{
              !printOrderData.cardName ? "" : printOrderData.cardName
            }}
          </div>
          <div v-if="printOrderData.isCustom" style="margin-top: 10px; border-bottom: 1px solid #000">
            备注：
            <div style="white-space: pre-wrap;" v-html="!printOrderData.postscript ? '' : printOrderData.postscript">
            </div>
          </div>
        </div>
        <div style="float: right; width: 50%; text-align: right">
          <div>
            <span style="text-align: left; width: 120px; display: inline-block">SubTotal(小计)：</span>¥{{
              printOrderData.goodsAmount }}
          </div>
          <div style="padding: 10px 0">
            <span style="text-align: left; width: 120px; display: inline-block">Discount(优惠)：</span>¥{{
              printOrderData.discount }}
          </div>
          <div>
            <span style="text-align: left; width: 120px; display: inline-block">Total(合计)：</span>¥{{
              printOrderData.moneyPaid }}
          </div>
        </div>
        <div style="clear: both"></div>
      </div>
      <div style="margin-top: 32px; text-align: center">
        <div>Customer Service(客服热线)：400-999-8611</div>
        <div style="display: flex; justify-content: center">
          <div style="flex: 1"></div>
          <div style="flex: 1"></div>
        </div>
      </div>
    </div>
    <template #footer>
      <a-button style="margin-right: 8px" @click="printVisible = false">关闭</a-button>
      <button class="arco-btn arco-btn-primary arco-btn-size-medium" v-print="printObj">
        打印
      </button>
    </template>
  </a-drawer>

  <a-modal width="80%" v-model:visible="histroyVisible" title="查看以往订单">
    <a-table :columns="histroyColumns" row-key="orderId" :loading="histroyLoading" :data="histroyData"
      @page-change="histroyPagination.pageChange" @page-size-change="histroyPagination.pageSizeChange"
      :pagination="histroyPagination" :bordered="false" :row-class="generateRowClass" :scroll="{ x: 1200, y: 500 }">
      <template #action="{ record }">
        <a-space>
          <a-button v-if="record.orderStatus == 8" style="width: 60px" size="mini"
            @click="viewRecord(record)">查看</a-button>
          <a-button :disabled="record.orderStatus == 8" style="width: 60px" size="mini"
            @click="editRecord(record)">编辑</a-button>
          <a-button @click="printOrder(record)" size="mini"
            :disabled="record.orderStatus >= 2 && record.orderStatus == 8">打印</a-button>
          <a-popconfirm content="确定取消该订单吗？" @ok="cancel(record)">
            <a-button style="width: 60px" v-if="record.orderStatus != 8" size="mini">{{
              record.orderStatus == 8 ? "已取消" : "取消" }}</a-button>
          </a-popconfirm>
          <a-popconfirm content="确认已联系客户吗？" @ok="sureOrder(record)">
            <a-button style="width: 60px" v-if="!record.packId && record.orderStatus != 8" size="mini">{{
              record.packId ? "已确认" : "确认" }}</a-button>
          </a-popconfirm>
        </a-space>
      </template>
      <template #addTimeText="{ record }">
        <div class="record-item">
          <div>
            <span class="addtime">下单:</span>{{ record.addTimeText }}
          </div>
          <div class="weight">
            <span>收货:</span>{{ record.shippingText }}
          </div>
        </div>
      </template>
      <template #shippingName="{ record }">
        <div class="record-item">
          <div>
            {{ record.shippingName ? record.shippingName : "—" }}
          </div>
        </div>
      </template>
      <template #payInfo="{ record }">
        <div class="record-item">
          <div>
            <span class="addtime">支付方式:</span>{{ record.payName }}
          </div>
          <div>
            <span class="addtime">支付状态:</span>{{ record.payStatus == 2 ? "已支付" : "未支付" }}
          </div>
        </div>
      </template>
      <template #orderMoney="{ record }">
        <div class="record-item">
          <div>
            <span class="addtime">订单:¥</span>{{ record.goodsAmount }}
          </div>
          <div><span class="addtime">应付:¥</span>{{ record.moneyPaid }}</div>
        </div>
      </template>
      <template #consignee="{ record }">
        <div class="record-item">
          <div>
            收货人：{{ record.consignee }} 【<span style="font-weight: 600">{{
              record.tel
            }}</span>】
          </div>
          <div style="font-size: 12px; padding-left: 48px">
            {{ record.address }}
          </div>
          <div class="flex flex-v-center" style="font-size: 12px">
            下单人：【<span>{{
              record.userName == "4009998611" ? "管理员" : record.userName
            }}</span>】
          </div>
        </div>
      </template>
      <template #productInfo="{ record }">
        <div class="record-item">
          <div v-for="item in record.goodList" :key="item.goodsAttrId">
            <div v-if="!item.goodsSn.includes('P25') && !item.goodsSn.includes('P22') && !item.goodsSn.includes('P24')">
              <span style="font-weight: 600;">{{ item.goodsName }}</span> {{ item.goodsAttr }} x {{ item.goodsNumber
              }}
            </div>
          </div>
        </div>
      </template>
    </a-table>
  </a-modal>

</template>

<style scoped lang="less">
.logo {
  font-size: 18px;
  text-align: center;
  color: #1c1f23;
  /* padding: 12px; */
  height: 55px;
  line-height: 55px;
  font-family: Inter, -apple-system, BlinkMacSystemFont, Segoe UI, PingFang SC,
    Hiragino Sans GB, Microsoft YaHei, Helvetica Neue, Helvetica, Arial,
    sans-serif;
  font-weight: 600;
}

.bg-base {
  background-color: rgba(243, 243, 245, 1);
}

.record-item {
  font-size: 12px;
}

.addtime {
  font-size: 13px;
  // color: #666;
}

.weight {
  font-weight: 600;
  font-size: 14px;
}

.create-order-con {
  background-color: #f9f9f9;
  overflow: hidden;
}

.good-content {
  height: 720px;
  width: 290px;
  position: relative;

  .goods-con {
    background-color: #fff;
    height: 670px;
    overflow-y: auto;
    overflow-x: hidden;
    padding-left: 10px;
    position: relative;

    .search-con {
      padding: 10px 0;
      background-color: #fff;
      position: sticky;
      top: 0;
      width: 100%;
      z-index: 99;
      border-bottom: 1px solid var(--color-neutral-3);
    }
  }

  .footer-page {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    padding: 10px 0;
    background-color: #fff;
    text-align: right;
    display: flex;
    justify-content: flex-end;
  }
}

.good-item,
.order-good-item {
  margin-bottom: 16px;

  .good-img {
    width: 100%;
    border-radius: 4px;
    position: relative;

    .good-attrs {
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      // background: rgba(0, 0, 0, 0.4);
      padding: 5px 0;

      .good-attr-btn {
        width: 52px;
        margin-left: 5px;
        margin-right: 5px;
        margin-top: 5px;
      }
    }

    img {
      width: 100%;
      height: 100%;
      border-radius: 4px;
      min-height: 100px;
    }
  }

  .good-info {
    font-size: 12px;
    padding: 3px 0;
    text-align: center;
    color: #111;
    font-weight: 600;
    width: 100%;
    white-space: nowrap;
    /* 不换行 */
    overflow: hidden;
    /* 隐藏溢出部分 */
    text-overflow: ellipsis;
    /* 显示省略号 */
  }
}

.buy-good-item {
  margin-bottom: 0;
  position: relative;

  .good-img {
    width: 100%;
    border-radius: 4px;
    position: relative;

    .good-attrs {
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      background: rgba(0, 0, 0, 0.2);
      padding: 5px 0;
      display: flex;
      align-items: center;

      .good-attr-btn {
        width: 50px;
        margin-left: 5px;
        margin-right: 5px;
        margin-top: 5px;
      }
    }

    img {
      width: 100%;
      height: 100%;
      border-radius: 4px;
      min-height: 100px;
    }
  }

  .good-info {
    position: absolute;
    top: 0;
    left: 0;
    background: rgba(0, 0, 0, 0.2);
    color: #fff;
    width: 100%;

    .good-name {
      font-weight: 600;
      padding: 0 5px;
      white-space: nowrap;
      /* 不换行 */
      overflow: hidden;
      /* 隐藏溢出部分 */
      text-overflow: ellipsis;
    }
  }
}

.option-btn {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  background: #fff;
}
</style>
